﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Hzexe.Wechat.SharpSDK.Message.Request
{
    /// <summary>
    /// 请求数据基类
    /// </summary>
    [Serializable]
    abstract public class RequestMessageBase : MessageBase
    {
        /// <summary>
        /// 原始的数据
        /// </summary>
        [XmlIgnore]
        public string originalxmlstr { get; set; }

        //日志对象
        protected static readonly log4net.ILog log = null;

        /// <summary>
        /// 消息编号
        /// </summary>
        public Int64  MsgId { get; set; }


         /// <summary>
        /// 消息类型与消息类的对应字典
        /// </summary>
        protected static Dictionary<string, Type> msgtypeDic;
        public RequestMessageBase()
        { 
            //填充当前类型的MsgType值
            base.MsgType = msgtypeDic.SingleOrDefault(k => k.Value == this.GetType()).Key;
        }
        static RequestMessageBase()
        {
            msgtypeDic = new Dictionary<string, Type>(10);
            msgtypeDic.Add("text",typeof(Message_In_Text));
            msgtypeDic.Add("image", typeof(Message_In_Image));
            msgtypeDic.Add("location", typeof(Message_In_Location));
            msgtypeDic.Add("link", typeof(Message_In_Link));
            msgtypeDic.Add("event", typeof(Message_In_Event));
            msgtypeDic.Add("voice", typeof(Message_In_Voice));
            msgtypeDic.Add("video", typeof(Message_In_Video));
            msgtypeDic.Add("unknown", typeof(Message_In_Unknown));
            log = log4net.LogManager.GetLogger(typeof(RequestMessageBase));
        }
        /// <summary>
        /// 解析收到的数据
        /// </summary>
        /// <param name="stream">收到的字节流对象</param>
        /// <returns></returns>
        public static dynamic Parse (System.IO.Stream stream)
        {
            RequestMessageBase msg = null;
            var doc = new System.Xml.XmlDocument();
            try
            {
                doc.Load (stream);
            }
            catch (Exception ex)
            {
                log.Fatal("解析消息失败", ex);
                throw ex;
            }
            var xmlstr = doc.OuterXml;

            var msgtype = doc.DocumentElement.SelectSingleNode("//MsgType").InnerText;
            Type type;
            if (msgtypeDic.Keys.Contains(msgtype))
               type= msgtypeDic[msgtype];
            else
                type = msgtypeDic["unknown"];       //解析成未知包

            var serializer = new XmlSerializer(type);
            stream.Position = 0;
            msg = serializer.Deserialize(stream) as RequestMessageBase;
            msg.originalxmlstr = xmlstr;    //把原始的传入的xml字符放入对象内
            return msg;
        }

        public override string ToString()
        {
            return this.originalxmlstr;
        }
    }
}
